import { request } from '@jl/common/utils';
import axios from 'axios';
import { useSceneStore } from '@/store/scene';
import { messageUtil } from '@jl/element-plus/utils';
import { createVNode, render } from 'vue';
import PanelTag from '@/components/gis-div/panel-poi.vue';
import { getNodeByTree } from '@/utils';

class EffectRequest {
  layer = null as any;
  timer = null as any;
  constructor(layer: API.Scene.ILayer) {
    const sceneStore = useSceneStore();
    const targetLayer = getNodeByTree(layer.layerName, sceneStore.layerTree);
    if (!targetLayer) return;
    this.layer = targetLayer;
    this.init(this.layer.effect.request.refrush);
  }

  init(time?: number) {
    const sceneStore = useSceneStore();
    if (!this.layer.effect.request.url) {
      return;
    }
    const param: any = {
      url: this.layer.effect.request.url,
      method: this.layer.effect.request.method,
      headers: {
        common: {
          // jlAuthUserTicket: this.layer.effect.request.ticket,
        },
      },
    };
    if (this.layer.effect.request.ticket) {
      param.headers.common.jlAuthUserTicket = this.layer.effect.request.ticket;
    }
    if (this.layer.effect.request.method === 'POST') {
      param.data = JSON.parse(this.layer.effect.request.data);
    }
    axios(param)
      .then((res: any) => {
        if (res.status !== 200) {
          messageUtil.warning('网络异常');
          this.timer && clearTimeout(this.timer);
          return;
        }
        // 服务返回错误信息
        if (res.data.code !== 0) {
          messageUtil.warning(res.data.msg);
          this.timer && clearTimeout(this.timer);
          return;
        }
        const targetLayer = getNodeByTree(this.layer.layerName, sceneStore.layerTree);
        if (!targetLayer) return;

        if (!res.data.data.length) {
          removeParticle(this.layer.layerName);
          return;
        }
        targetLayer.effect.requestData = Object.keys(res.data.data[0]).map((key: string) => {
          return {
            label: key,
            value: res.data.data[0][key],
          };
        });
        // 特效判定
        if (targetLayer.type === 'gltfmodel') {
          targetLayer.effect.list.forEach((item: any) => {
            addParticle(item, targetLayer.effect.requestData, this.layer.layerName);
          });
        }
        // 更新dom
        if (targetLayer.type === 'div') {
          updateDom(targetLayer);
        }

        if (time && targetLayer.effect.request.isRefrush) {
          this.timer = setTimeout(() => {
            this.init(time);
          }, time * 1000);
        }
      })
      .catch(() => {
        this.timer && clearTimeout(this.timer);
      });
  }

  refrush(time: number) {
    clearTimeout(this.timer);
    this.init(time);
  }

  destroy() {
    this.layer = null;
    clearTimeout(this.timer);
  }
}

export const layerRequestInsMap = new Map();

export const addlayerRequestIns = (layer: API.Scene.ILayer) => {
  if (layerRequestInsMap.has(layer.layerName)) {
    const ins: any = layerRequestInsMap.get(layer.layerName);
    if (layer.effect) {
      ins.refrush(layer.effect.request.refrush);
    }
    return;
  }
  layerRequestInsMap.set(layer.layerName, new EffectRequest(layer));
};

export const deletelayerRequestIns = (layer: API.Scene.ILayer) => {
  const ins: any = layerRequestInsMap.get(layer.layerName);
  if (ins) {
    ins.destroy();
    layerRequestInsMap.delete(layer.layerName);
  }
  // 删除场景特效
  if (layer.type === 'gltfmodel' && !layer.actualType) {
    removeParticle(layer.layerName);
  }
};

// 删除特效
function removeParticle(layerName: string) {
  const { cimInstance } = window;
  const sceneStore = useSceneStore();
  const targetLayer = getNodeByTree(layerName, sceneStore.layerTree);
  if (!targetLayer || !targetLayer.effect) return;
  targetLayer.effect.list.forEach((item: any) => {
    if (item.name) {
      cimInstance.api.destroyCimParticle(item.name);
    }
  });
}

// 设置特效
export function addParticle(item: any, data: any, layerName: string) {
  const { cimInstance } = window;
  if (item.field && item.value.toString() !== '' && item.name) {
    let repFieldValue = null;
    for (const v of data) {
      if (v.label === item.field) {
        repFieldValue = v.value;
        break;
      }
    }

    const isValueNumber = isNaN(item.value);
    // 等于判定
    const dengyu = isValueNumber
      ? repFieldValue === item.value
      : repFieldValue === Number(item.value);
    // 大于判定
    const dayu = repFieldValue > item.value;
    // 大于等于判定
    const dayudengyu = dengyu || dayu;
    // 小于判定
    const xiaoyu = repFieldValue < item.value;
    // 小于等于判定
    const xiaoyudengyu = dengyu || xiaoyu;

    if (
      (dengyu && item.type === '1') ||
      (dayu && item.type === '2') ||
      (dayudengyu && item.type === '3') ||
      (xiaoyu && item.type === '4') ||
      (xiaoyudengyu && item.type === '5')
    ) {
      const particleConfig = {
        enable: true,
        dataSourceUrl:
          'http://192.168.50.85:15055/shouqiandemo/zhengtai/' +
          'particle/json/' +
          item.name +
          '.json',
        owner: layerName,
        name: item.name,
        useOwnerModelConstructCenter: false,
      };
      cimInstance.api.createParticleSystem(particleConfig);
    } else {
      cimInstance.api.destroyCimParticle(item.name);
    }
  }
}

// 更新dom
export function updateDom(layer: API.Scene.ILayer) {
  const vmInstance = createVNode(PanelTag, {
    data: {
      ...layer,
    },
  });
  const targetAllDom: any = document.querySelectorAll(`.${layer.layerName}`);
  targetAllDom.forEach((dom: any) => {
    render(vmInstance, dom);
  });
}
